package com.vertxsample.samples.testgateway.nodeserver

import io.vertx.core.DeploymentOptions
import io.vertx.core.Vertx
import io.vertx.core.json.JsonObject
import io.vertx.ext.consul.CheckOptions
import io.vertx.ext.consul.ConsulClient
import io.vertx.ext.consul.ConsulClientOptions
import io.vertx.ext.consul.ServiceOptions
import org.apache.logging.log4j.LogManager
import java.net.InetAddress


class App {

    companion object {
        val logger = LogManager.getLogger(App::class.java.getName())
        @JvmStatic
        fun main(args: Array<String>) {
            val vertx = Vertx.vertx()
            val port =Integer.parseInt( System.getProperty("http.port"))
            val consul_host =System.getProperty("consul.host") //consul地址
            val consul_check_interval =System.getProperty("consul.check.interval") //consul健康检查间隔时间
            val consul_port=Integer.parseInt( System.getProperty("consul.port"))  //consul 端口
            val consulClientOptions = ConsulClientOptions(  )
            consulClientOptions.host=consul_host
            consulClientOptions.port=consul_port
            var consulClient = ConsulClient.create(vertx, consulClientOptions)

            //获取配置
            consulClient.getValue("config/application,test/data", { res ->

                if (res.succeeded()) {
                    try {
                        val options= JsonObject(res.result().value)

                        //线程池配置
                        var deployMentOptions = DeploymentOptions().setWorker(true)
                            .setWorkerPoolName(options.getString("vertx.workerPoolName"))
                            .setWorkerPoolSize(options.getInteger("vertx.workerPoolSize"))

                        //部署web服务
                        vertx.deployVerticle(StarterVerticle(options,port),deployMentOptions)
                    }catch (e :Exception){
                        logger.error("",e)
                    }

                } else {
                    logger.error("", res.cause())
                    vertx.close()
                }
            })

            val opts = ServiceOptions()
                .setName("gateway-nodeserver")
                .setId("gateway-nodeserver-"+InetAddress.getLocalHost().hostAddress+":"+port)
                .setCheckOptions(CheckOptions().setHttp("http://"+InetAddress.getLocalHost().hostAddress+":"+port+"/health")
                    .setInterval(consul_check_interval))
                .setAddress(InetAddress.getLocalHost().hostAddress)
                .setPort(port)
            consulClient.registerService(opts) { res ->
                if (res.succeeded()) {
                    logger.info("Service:gateway-nodeserver successfully registered")
                } else {
                    logger.error("Service:gateway-nodeserver fail registered",res.cause())
                }

            }


        }
    }
}